<template>
  <div class="admin-data-test-container">
    <div class="test-card">
      <h2>🗄️ 管理员数据测试</h2>
      
      <div class="test-section">
        <h3>数据库初始化SQL</h3>
        <p>请在数据库中执行以下SQL语句来创建管理员数据：</p>
        <div class="sql-code">
          <pre>{{ sqlScript }}</pre>
        </div>
        <el-button @click="copySQLToClipboard" type="primary">复制SQL到剪贴板</el-button>
      </div>

      <div class="test-section">
        <h3>测试数据验证</h3>
        <p>验证管理员数据是否正确创建</p>
        <el-button @click="testAdminData" type="success">验证管理员数据</el-button>
        <p class="result">{{ testResult }}</p>
      </div>

      <div class="test-section">
        <h3>手动登录测试</h3>
        <p>使用创建的管理员账号进行登录测试</p>
        <el-form :model="adminForm" label-width="100px" style="max-width: 400px;">
          <el-form-item label="管理员账号">
            <el-input v-model="adminForm.username" placeholder="请输入管理员账号" />
          </el-form-item>
          <el-form-item label="管理员密码">
            <el-input v-model="adminForm.password" type="password" placeholder="请输入管理员密码" />
          </el-form-item>
          <el-form-item>
            <el-button @click="testLogin" :loading="loading" type="primary">测试登录</el-button>
          </el-form-item>
        </el-form>
        <p class="result">{{ loginResult }}</p>
      </div>

      <div class="test-section">
        <h3>预设账号</h3>
        <p>以下是预设的管理员账号，请确保数据库中存在这些数据：</p>
        <el-table :data="adminAccounts" style="width: 100%">
          <el-table-column prop="username" label="用户名" width="150" />
          <el-table-column prop="password" label="密码" width="150" />
          <el-table-column prop="description" label="说明" />
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button size="small" @click="useAccount(scope.row)">使用</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { adminLogin } from '@/utils/apiService'

// 状态
const loading = ref(false)
const testResult = ref('')
const loginResult = ref('')

// 管理员表单
const adminForm = reactive({
  username: 'admin',
  password: 'admin123'
})

// 预设管理员账号
const adminAccounts = ref([
  { username: 'admin', password: 'admin123', description: '默认管理员' },
  { username: 'superadmin', password: 'super123', description: '超级管理员' },
  { username: 'manager', password: 'manager123', description: '管理员' }
])

// SQL初始化脚本
const sqlScript = `-- 管理员表初始化
CREATE TABLE IF NOT EXISTS \`administrator\` (
  \`administratorId\` bigint NOT NULL AUTO_INCREMENT COMMENT '管理员ID',
  \`administratorName\` varchar(50) NOT NULL COMMENT '管理员姓名',
  \`administratorPassword\` varchar(100) NOT NULL COMMENT '管理员密码',
  PRIMARY KEY (\`administratorId\`),
  UNIQUE KEY \`uk_administrator_name\` (\`administratorName\`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='管理员表';

-- 插入管理员数据
INSERT IGNORE INTO \`administrator\` (\`administratorName\`, \`administratorPassword\`) VALUES 
('admin', 'admin123'),
('superadmin', 'super123'),
('manager', 'manager123');

-- 查询验证
SELECT * FROM \`administrator\`;`

// 复制SQL到剪贴板
const copySQLToClipboard = async () => {
  try {
    await navigator.clipboard.writeText(sqlScript)
    ElMessage.success('SQL脚本已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败，请手动复制')
  }
}

// 测试管理员数据
const testAdminData = async () => {
  try {
    testResult.value = '正在验证管理员数据...'
    
    // 尝试使用默认账号登录来验证数据是否存在
    const response = await adminLogin({
      username: 'admin',
      password: 'admin123'
    })
    
    if (response.data.code === "200" || response.data.code === 200) {
      testResult.value = '✅ 管理员数据验证成功！数据库中存在有效的管理员账号。'
      ElMessage.success('管理员数据验证成功')
    } else {
      testResult.value = `❌ 管理员数据验证失败: ${response.data.message}`
      ElMessage.error('管理员数据验证失败')
    }
  } catch (error) {
    if (error.response?.status === 500) {
      testResult.value = '❌ 数据库连接失败或管理员表不存在，请先执行上面的SQL脚本'
    } else {
      testResult.value = `❌ 验证失败: ${error.response?.data?.message || error.message}`
    }
    ElMessage.error('管理员数据验证失败')
  }
}

// 测试登录
const testLogin = async () => {
  loading.value = true
  try {
    loginResult.value = '正在测试登录...'
    
    const response = await adminLogin({
      username: adminForm.username,
      password: adminForm.password
    })
    
    if (response.data.code === "200" || response.data.code === 200) {
      loginResult.value = `✅ 登录成功！
Token: ${response.data.data.info?.substring(0, 20)}...
管理员信息: ${JSON.stringify(response.data.data.loginAdmin, null, 2)}`
      ElMessage.success('登录测试成功')
    } else {
      loginResult.value = `❌ 登录失败: ${response.data.message}`
      ElMessage.error('登录测试失败')
    }
  } catch (error) {
    loginResult.value = `❌ 登录异常: ${error.response?.data?.message || error.message}`
    ElMessage.error('登录测试异常')
  } finally {
    loading.value = false
  }
}

// 使用预设账号
const useAccount = (account) => {
  adminForm.username = account.username
  adminForm.password = account.password
  ElMessage.info(`已设置账号: ${account.username}`)
}
</script>

<style scoped>
.admin-data-test-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.test-card {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.test-card h2 {
  color: #2c3e50;
  margin-bottom: 30px;
  text-align: center;
}

.test-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #e1e8ed;
  border-radius: 8px;
  background: #f8f9fa;
}

.test-section h3 {
  margin-top: 0;
  color: #34495e;
  margin-bottom: 15px;
}

.test-section p {
  color: #7f8c8d;
  margin-bottom: 15px;
}

.sql-code {
  background: #2d3748;
  color: #e2e8f0;
  padding: 20px;
  border-radius: 8px;
  margin: 15px 0;
  font-family: 'Courier New', monospace;
  font-size: 14px;
  overflow-x: auto;
}

.sql-code pre {
  margin: 0;
  white-space: pre-wrap;
}

.result {
  margin-top: 15px;
  padding: 15px;
  background: #ffffff;
  border-radius: 6px;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  white-space: pre-wrap;
  word-break: break-all;
  border-left: 4px solid #3498db;
  max-height: 300px;
  overflow-y: auto;
}

.el-button {
  margin-right: 10px;
  margin-bottom: 10px;
}
</style>
